package org.jeecgframework.web.controller;

import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.util.PinyinUtil;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.web.service.CbsVerificationCodeServiceI;
import org.jeecgframework.web.service.WxCommonService;
import org.jeecgframework.web.service.ZyCommonService;
import org.jeecgframework.web.system.pojo.base.*;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.style.DefaultValueStyler;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by 大伟 on 2017/1/6.
 * Description
 */
@Controller
@RequestMapping("/wxMenuController")
public class WxMenuController {

    @Autowired
    private WxCommonService wxCommonService;

    @Autowired
    private ZyCommonService zyCommonService;

    @Autowired
    private SystemService systemService;
    @Autowired
    private CbsVerificationCodeServiceI verificationCodeService;

    private static String PREFIX_ADD_PRODUCT = "com/wx/added_product";
    private static String PREFIX_SELF_SERVICE = "com/wx/self_service";

    private static String PREFIX_CENTER = "com/wx/personal_center";

    public TSUser genUser(HttpServletRequest request){
        TSUser u = ResourceUtil.getSessionUserName();
        if(null == u){
            String openId = oConvertUtils.getString(request.getSession().getAttribute("openId")) ;
            u = zyCommonService.findUniqueByProperty(TSUser.class,"openId", openId);
        }
        return u;
    }


    @RequestMapping(params = "subSuc")
    public String goSubSuccess(String param, ModelMap map, HttpServletRequest request){
        String openId = oConvertUtils.getString(request.getSession().getAttribute("openId"));
        String isUser="is";
        List<TSUser> userList = systemService.findHql("from TSUser where openId = ?", openId);
        if(userList==null || userList.size()<=0){
            isUser="no";
        }
        map.addAttribute("msg",param);
        map.addAttribute("isUser",isUser);
        map.addAttribute("serviceType",oConvertUtils.getString(request.getParameter("type")));
        map.addAttribute("phone",oConvertUtils.getString(request.getParameter("phone")));
        return PREFIX_ADD_PRODUCT + "/sub-suc";
    }

    /**
     * Description 引擎翻新
     */
    @RequestMapping(params = "yqfx")
    public String goYqfxIndex(ModelMap map){
        return PREFIX_ADD_PRODUCT+"/yqfx/mid";
    }

    @RequestMapping(params = "yqfxOrd")
    public String goYqfxOrd(String id,String details,ModelMap map,HttpServletRequest request){
        map.put("detail",details);
        TSUser u = genUser(request);
        CbsYqReconditionEntity c = wxCommonService.get(CbsYqReconditionEntity.class, oConvertUtils.getString(id));
        if(null != u){
            if(c == null){
                c = new CbsYqReconditionEntity();
            }
            c.setContactsName(u.getRealName());
            c.setContactsPhone(u.getMobilePhone());
            TSBaseUser bu = wxCommonService.get(TSBaseUser.class, u.getId());
            if(bu != null){
                if(bu.getAuthenticationLevel() !=null && bu.getAuthenticationLevel().equals("2")){//钻石（原金牌）用户
                    List<ZyContactsEntity> cts = wxCommonService.findByProperty(ZyContactsEntity.class, "tsBaseUser.id", bu.getId());
                    List<CbsWxUserBindEntity> wubs = wxCommonService.findByProperty(CbsWxUserBindEntity.class, "openId", bu.getOpenId());
                    if(cts != null && cts.size() > 0 && cts.get(0).getBelongCinema() != null){
                        c.setCinemaName(cts.get(0).getBelongCinema().getName());
                    }
                    if(wubs != null && wubs.size() > 0){
                        c.setCinemaChain(wubs.get(0).getChainName());
                    }
                }
            }
        }
        map.put("page",c);
        return PREFIX_ADD_PRODUCT + "/yqfx/ord";
    }


    @RequestMapping(params = "ggfx")
    public String goGgfxIndex(ModelMap map){
        return PREFIX_ADD_PRODUCT + "/ggfx/mid";
    }

    @RequestMapping(params = "ggfxOrd")
    public String goGgfxOrd(String id,String details,ModelMap map,HttpServletRequest request){
        map.put("detail",details);
        TSUser u = genUser(request);
        CbsGgReconditionEntity c = wxCommonService.get(CbsGgReconditionEntity.class, oConvertUtils.getString(id));
        if(null != u){
            c = null == c ? new CbsGgReconditionEntity() : c;
            c.setContactsName(u.getRealName());
            c.setContactsPhone(u.getMobilePhone());
            TSBaseUser bu = wxCommonService.get(TSBaseUser.class, u.getId());
            if(bu != null){
                if(bu.getAuthenticationLevel() !=null && bu.getAuthenticationLevel().equals("2")){//钻石（原金牌）用户
                    List<ZyContactsEntity> cts = wxCommonService.findByProperty(ZyContactsEntity.class, "tsBaseUser.id", bu.getId());
                    List<CbsWxUserBindEntity> wubs = wxCommonService.findByProperty(CbsWxUserBindEntity.class, "openId", bu.getOpenId());
                    if(cts != null && cts.size() > 0 && cts.get(0).getBelongCinema() != null){
                        c.setCinemaName(cts.get(0).getBelongCinema().getName());
                    }
                    if(wubs != null && wubs.size() > 0){
                        c.setCinemaChain(wubs.get(0).getChainName());
                    }
                }
            }
        }
        map.put("page",c);
        return PREFIX_ADD_PRODUCT + "/ggfx/ord";
    }

    @RequestMapping(params = "sbwb")
    public String goSbwb(ModelMap map){
        return PREFIX_ADD_PRODUCT + "/sbwb/mid";
    }

    /*
     * 跳转至申请延保
     * */
    @RequestMapping(params = "sbwbOrd")
    public String goSbwbOrd(ModelMap map, HttpServletRequest request){
        TSUser u = genUser(request);
        if(null != u){
            CbsExtWarrantyEntity c = new CbsExtWarrantyEntity();
            c.setContactsName(u.getRealName());
            c.setContactsPhone(u.getMobilePhone());
            TSBaseUser bu = wxCommonService.get(TSBaseUser.class, u.getId());
            if(bu != null){
                if(bu.getAuthenticationLevel() !=null && bu.getAuthenticationLevel().equals("2")){//钻石（原金牌）用户
                    List<ZyContactsEntity> cts = wxCommonService.findByProperty(ZyContactsEntity.class, "tsBaseUser.id", bu.getId());
                    List<CbsWxUserBindEntity> wubs = wxCommonService.findByProperty(CbsWxUserBindEntity.class, "openId", bu.getOpenId());
                    if(cts != null && cts.size() > 0 && cts.get(0).getBelongCinema() != null){
                        c.setCinemaName(cts.get(0).getBelongCinema().getName());
                    }
                    if(wubs != null && wubs.size() > 0){
                        c.setCinemaChain(wubs.get(0).getChainName());
                    }
                }
            }
            map.put("page",c);
        }

        return PREFIX_ADD_PRODUCT + "/sbwb/ord";
    }


    @RequestMapping(params = "sbyj")
    public String goSbyj(ModelMap map){
        return PREFIX_ADD_PRODUCT + "/sbyj/mid";
    }

    @RequestMapping(params = "sbyjOrd")
    public String goSbyjOrd(String id,String details,ModelMap map, HttpServletRequest request){
        map.put("detail",details);
        TSUser u = genUser(request);
        CbsMerchineMoveEntity c = wxCommonService.get(CbsMerchineMoveEntity.class, oConvertUtils.getString(id));
        if(null != u){
            c = null == c ? new CbsMerchineMoveEntity() : c;
            c.setContactsName(u.getRealName());
            c.setContactsPhone(u.getMobilePhone());
            TSBaseUser bu = wxCommonService.get(TSBaseUser.class, u.getId());
            if(bu != null){
                if(bu.getAuthenticationLevel() !=null && bu.getAuthenticationLevel().equals("2")){//钻石（原金牌）用户
                    List<ZyContactsEntity> cts = wxCommonService.findByProperty(ZyContactsEntity.class, "tsBaseUser.id", bu.getId());
                    List<CbsWxUserBindEntity> wubs = wxCommonService.findByProperty(CbsWxUserBindEntity.class, "openId", bu.getOpenId());
                    if(cts != null && cts.size() > 0 && cts.get(0).getBelongCinema() != null){
                        c.setCinemaName(cts.get(0).getBelongCinema().getName());
                    }
                    if(wubs != null && wubs.size() > 0){
                        c.setCinemaChain(wubs.get(0).getChainName());
                    }
                }
            }
        }
        map.put("page",c);
        return PREFIX_ADD_PRODUCT + "/sbyj/ord";
    }


    @RequestMapping(params = "rzpx")
    public String goRzpx(ModelMap map){
        return PREFIX_ADD_PRODUCT + "/rzpx/mid";
    }

    @RequestMapping(params = "xjyy")
    public String goXjyy(ModelMap map,HttpServletRequest request){
        map.put("sn",request.getParameter("sn"));
        return PREFIX_ADD_PRODUCT + "/xjyy/mid";
    }
    /**
     *
     * 巡检介绍页面
     * */
    @RequestMapping(params = "xjjs")
    public String goXjjs(ModelMap map,HttpServletRequest request){
        return PREFIX_SELF_SERVICE + "/xjjs";
    }
    @RequestMapping(params = "xjyyOrd")
    public String goxjyyOrd(String id,String details,ModelMap map, HttpServletRequest request){
        map.put("detail",details);
        TSUser u = genUser(request);
        CbsInsApplicationEntity c = wxCommonService.get(CbsInsApplicationEntity.class, oConvertUtils.getString(id));
        if(null != u){
            c = null == c ? new CbsInsApplicationEntity() : c;
            c.setContactsName(u.getRealName());
            c.setContactsPhone(u.getMobilePhone());
        }
        map.put("page",c);
        return PREFIX_ADD_PRODUCT + "/xjyy/ord";
    }

    @RequestMapping(params = "ordList")
    public String goOrdList(@RequestParam(defaultValue = "0",required = false) int type, String phone, ModelMap map){
        WxCommonService.ServiceEnum se = WxCommonService.ServiceEnum.getService(type);
        map.put("results",wxCommonService.getList(se,phone));
        map.put("serviceType", se.getMsg());
        map.put("type", type);
        return PREFIX_ADD_PRODUCT + "/ord-list";
    }
    @RequestMapping(params = "ordListNew")
    public String goOrdListNew(@RequestParam(defaultValue = "0",required = false) int type, String phone, ModelMap map){
        WxCommonService.ServiceEnum se = WxCommonService.ServiceEnum.getService(type);
        map.put("results",wxCommonService.getListNew(se,phone));
        map.put("serviceType", se.getMsg());
        map.put("type", type);
        //查询所有服务单状态
        List<TSType> statusList=systemService.findHql("from TSType where TSTypegroup.typegroupcode='cbsServiceState'");
        map.put("statusList", statusList);
        return PREFIX_ADD_PRODUCT + "/ord-list";
    }
    @RequestMapping(params = "checkVerify")
    @ResponseBody
    public AjaxJson checkVerify(String verifyCode,HttpServletRequest request){
        AjaxJson result = new AjaxJson();
        if(!verificationCodeService.checkVerifyCode(request.getSession().getId(),verifyCode)){
            result.setSuccess(false);
            result.setMsg("验证码错误");
        }
        return result;
    }

    @RequestMapping(params = "selfService")
    public String selfService(ModelMap map){
        return PREFIX_ADD_PRODUCT + "/self-service";
    }

    @RequestMapping(params = "serviceUser")
    @ResponseBody
    public AjaxJson serviceUser(String phoneNum,String contactName,HttpServletRequest request){
        AjaxJson result = new AjaxJson();
        wxCommonService.initUserWithPhoneAndName(phoneNum,contactName,request);
        return result;
    }

    @RequestMapping(params = "sendVerifyCode")
    @ResponseBody
    public AjaxJson sendWxPhoneCode(HttpServletRequest request, String phoneNumber) {
        AjaxJson json = new AjaxJson();
        json.setMsg("发送成功");
        HttpSession session = request.getSession();
        String sessionId = session.getId();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("liveTime", StaticValue.SEND_RANDOMCODE_LIVETIME);
        json = zyCommonService.sendRandomCode(sessionId, phoneNumber, StaticValue.SEND_RANDOMCODE_LIVETIME, "sms_wx_create.ftl", map, StaticValue.RANDOMCODE_WX_CREATE);
        return json;
    }

    /**
     * @author xiul
     * 2017-4-12 下午2:56:13
     * Description 快速报修 跳转
     */
    @RequestMapping(params="quickRepair")
    public ModelAndView quickRepair(HttpServletRequest request){
        TSUser user = genUser(request);
        if(user != null){
            ZyContactsEntity contact = zyCommonService.findUniqueByProperty(ZyContactsEntity.class, "tsBaseUser.id", user.getId());
            if(contact != null){
                request.setAttribute("ct", contact);
                if(contact.getBelongCinema() != null){
                    String belongCmName = contact.getBelongCinema().getName();
                    request.setAttribute("belongCmName", belongCmName);
                }
            }
            if(StringUtil.isNotEmpty(user.getOpenId())){
                request.setAttribute("openId",user.getOpenId());
            }
        }
        return new ModelAndView("com/wx/repair_query/quick_repair");
    }


    @RequestMapping(params = "xjbg")
    public String goXjbg(ModelMap map,HttpServletRequest request){
        map.put("sn",request.getParameter("sn"));
        return PREFIX_ADD_PRODUCT + "/xjbg/mid";
    }



    //测试微信发送模板消息接口
    @RequestMapping(params="testSendMsg")
    public void testSendMsg() throws Exception{
        List<Map<String,String>> list=new ArrayList<>();
        Map<String,String> map1=new HashMap<>();
        Map<String,String> map2=new HashMap<>();
        Map<String,String> map3=new HashMap<>();
        map1.put("openid","oacqX1XUgi_YdMy75LvdYUveLBD0");
        map1.put("message","aaa");

        list.add(map1);
        String jsonString=wxCommonService.sendMsgForWx(list);
        System.out.println("jsonString:"+jsonString);

    }


    /**
     * @author mhg
     * 2018-5-31
    * 新公众号跳转至光管翻新申请页面
    * */
    @RequestMapping(params = "ggfxOrdNew")
    public String goGgfxOrdNew(String id,String details,ModelMap map,HttpServletRequest request){
        map.put("detail",details);
        TSUser u = genUser(request);
        String cinemaName="";
        if(null != u){
            TSBaseUser bu = wxCommonService.get(TSBaseUser.class, u.getId());
            if(bu != null){
                List<ZyContactsEntity> cts = wxCommonService.findByProperty(ZyContactsEntity.class, "tsBaseUser.id", bu.getId());
                if(cts != null && cts.size() > 0 && cts.get(0) != null){
                    cinemaName=cts.get(0).getCinemaName();
                }
                if(bu.getAuthenticationLevel() !=null && bu.getAuthenticationLevel().equals("2")){//钻石（原金牌）用户
                    List<CbsWxUserBindEntity> wubs = wxCommonService.findByProperty(CbsWxUserBindEntity.class, "openId", bu.getOpenId());
                    if(wubs != null && wubs.size() > 0){
                        cinemaName=wubs.get(0).getCinemaName();
                        map.put("cinemaChain",wubs.get(0).getChainName());
                    }
                }
            }
        }
        map.put("page",u);
        map.put("cinemaName",cinemaName);
        map.put("serviceDate",new Date());
        return PREFIX_ADD_PRODUCT + "/ggfx/ord";
    }
    /**
     * @author mhg
     * 2018-5-31
    * 新公众号跳转至巡检预约申请页面
    * */
    @RequestMapping(params = "xjyyOrdNew")
    public String xjyyOrdNew(String id,String details,ModelMap map,HttpServletRequest request) throws Exception{
        map.put("detail",details);
        TSUser u = genUser(request);
        String cinemaName="";
        if(null != u){
            TSBaseUser bu = wxCommonService.get(TSBaseUser.class, u.getId());
            if(bu != null){
                List<ZyContactsEntity> cts = wxCommonService.findByProperty(ZyContactsEntity.class, "tsBaseUser.id", bu.getId());
                if(cts != null && cts.size() > 0 && cts.get(0) != null){
                    cinemaName=cts.get(0).getCinemaName();
                }
                if(bu.getAuthenticationLevel() !=null && bu.getAuthenticationLevel().equals("2")){//钻石（原金牌）用户
                    List<CbsWxUserBindEntity> wubs = wxCommonService.findByProperty(CbsWxUserBindEntity.class, "openId", bu.getOpenId());
                    if(wubs != null && wubs.size() > 0){
                        cinemaName=wubs.get(0).getCinemaName();
                        map.put("cinemaChain",wubs.get(0).getChainName());
                    }
                }
            }
        }
        map.put("page",u);
        map.put("cinemaName",cinemaName);
        Calendar date = Calendar.getInstance();
        String year=String.valueOf(date.get(Calendar.YEAR)+1);
        String date1=year+"-01";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Date date2=sdf.parse(date1);
        map.put("serviceDate",date2);
        map.put("sn",request.getParameter("sn"));
        return PREFIX_ADD_PRODUCT + "/xjyy/ord";
    }
    /**
     * @author mhg
     * 2018-5-31
    * 新公众号跳转至设备维保申请页面
    * */
    @RequestMapping(params = "sbwbOrdNew")
    public String sbwbOrdNew(String id,String details,ModelMap map,HttpServletRequest request){
        map.put("detail",details);
        TSUser u = genUser(request);
        String cinemaName="";
        if(null != u){
            TSBaseUser bu = wxCommonService.get(TSBaseUser.class, u.getId());
            if(bu != null){
                List<ZyContactsEntity> cts = wxCommonService.findByProperty(ZyContactsEntity.class, "tsBaseUser.id", bu.getId());
                if(cts != null && cts.size() > 0 && cts.get(0)!= null){
                    cinemaName=cts.get(0).getCinemaName();
                }
                if(bu.getAuthenticationLevel() !=null && bu.getAuthenticationLevel().equals("2")){//钻石（原金牌）用户
                    List<CbsWxUserBindEntity> wubs = wxCommonService.findByProperty(CbsWxUserBindEntity.class, "openId", bu.getOpenId());
                    if(wubs != null && wubs.size() > 0){
                        cinemaName=wubs.get(0).getCinemaName();
                        map.put("cinemaChain",wubs.get(0).getChainName());
                    }
                }
            }
        }
        map.put("page",u);
        map.put("cinemaName",cinemaName);
        map.put("serviceDate",new Date());
        return PREFIX_ADD_PRODUCT + "/sbwb/ord";
    }
    /**
     * @author mhg
     * 2018-5-31
    * 新公众号跳转至设备移机申请页面
    * */
    @RequestMapping(params = "sbyjOrdNew")
    public String sbyjOrdNew(String id,String details,ModelMap map,HttpServletRequest request){
        map.put("detail",details);
        TSUser u = genUser(request);
        String cinemaName="";
        if(null != u){
            TSBaseUser bu = wxCommonService.get(TSBaseUser.class, u.getId());
            if(bu != null){
                List<ZyContactsEntity> cts = wxCommonService.findByProperty(ZyContactsEntity.class, "tsBaseUser.id", bu.getId());
                if(cts != null && cts.size() > 0 && cts.get(0)!= null){
                    cinemaName=cts.get(0).getCinemaName();
                }
                if(bu.getAuthenticationLevel() !=null && bu.getAuthenticationLevel().equals("2")){//钻石（原金牌）用户
                    List<CbsWxUserBindEntity> wubs = wxCommonService.findByProperty(CbsWxUserBindEntity.class, "openId", bu.getOpenId());
                    if(wubs != null && wubs.size() > 0){
                        cinemaName=wubs.get(0).getCinemaName();
                        map.put("cinemaChain",wubs.get(0).getChainName());
                    }
                }
            }
        }
        map.put("page",u);
        map.put("cinemaName",cinemaName);
        map.put("serviceDate",new Date());
        return PREFIX_ADD_PRODUCT + "/sbyj/ord";
    }
    /**
     * @author mhg
     * 2018-5-31
    * 新公众号跳转至引擎翻新申请页面
    * */
    @RequestMapping(params = "yqfxOrdNew")
    public String yqfxOrdNew(String id,String details,ModelMap map,HttpServletRequest request){
        map.put("detail",details);
        TSUser u = genUser(request);
        String cinemaName="";
        if(null != u){
            TSBaseUser bu = wxCommonService.get(TSBaseUser.class, u.getId());
            if(bu != null){
                List<ZyContactsEntity> cts = wxCommonService.findByProperty(ZyContactsEntity.class, "tsBaseUser.id", bu.getId());
                if(cts != null && cts.size() > 0 && cts.get(0) != null){
                    cinemaName=cts.get(0).getCinemaName();
                }
                if(bu.getAuthenticationLevel() !=null && bu.getAuthenticationLevel().equals("2")){//钻石（原金牌）用户
                    List<CbsWxUserBindEntity> wubs = wxCommonService.findByProperty(CbsWxUserBindEntity.class, "openId", bu.getOpenId());
                    if(wubs != null && wubs.size() > 0){
                        cinemaName=wubs.get(0).getCinemaName();
                        map.put("cinemaChain",wubs.get(0).getChainName());
                    }
                }
            }
        }
        map.put("page",u);
        map.put("cinemaName",cinemaName);
        map.put("serviceDate",new Date());
        return PREFIX_ADD_PRODUCT + "/yqfx/ord";
    }






    /**
     * @author mhg
     * 2018-5-31
     * Description 增值产品 提交订单前的 发送验证码
     */
    @ResponseBody
    @RequestMapping(params="sendVerifyCodeNew")
    public AjaxJson sendVerifyCodeNew(HttpServletRequest request){
        AjaxJson json = new AjaxJson();
        String phoneNo = oConvertUtils.getString(request.getParameter("phoneNumber"));
        String busType = oConvertUtils.getString(request.getParameter("busType"));
        String serviceType = oConvertUtils.getString(request.getParameter("serviceType"));
        Integer timeOut = StaticValue.SEND_RANDOMCODE_TIMEOUT;

        Map<String, Object> templeteMap = new HashMap<String, Object>();
        templeteMap.put("phoneLastFour", phoneNo.substring(7));
        templeteMap.put("liveTime", timeOut);
        templeteMap.put("serviceType", serviceType);
        json = zyCommonService.sendRandomCode(request.getSession().getId(), phoneNo, timeOut, "sms_added_product.ftl", templeteMap, busType);
        return json;
    }

    /**
     * @author mhg
     *
     * Description 检查验证码
     */
    @ResponseBody
    @RequestMapping(params = "checkVerifyNew")
    public AjaxJson checkVerifyNew(HttpServletRequest request){
        AjaxJson result = new AjaxJson();
        String busType = request.getParameter("busType");
        String verifyCode = request.getParameter("verifyCode");
        System.out.println("SESSIONID：" +request.getSession().getId());
        result = zyCommonService.checkUserRandomCodeTimeout(request.getSession().getId(), busType, verifyCode);
//        String message="";
//        result.setMsg(message);
        return result;
    }
}
